<?php
//项目订单

namespace app\admin\controller;

use app\admin\model\ComponentExceptionInfoRe;
use app\admin\model\ProjectsDrawingLib;
use app\admin\service\ProjectsOrder as ProjectsOrderS;
use app\admin\model\ProjectsOrder as ProjectsOrderM;
use app\admin\model\Projects as ProjectsM;
use think\facade\Config;
use think\facade\Db;

class ProjectsOrder extends Base
{
    protected $middleware = ['app\admin\middleware\TableFields::class'];  //获取表结构，添加在返回数据中
    public $index_not_display_fields = 'update_time,price,invoice_status,exception_type,drawing_img';  //字段不会在后台列表页，字段选择中显示
    //数据表中不存在的字段，后端页面有显示，在控制器拼接的字段
    public $additional_fields_list = [
        'schedule' =>['name' => 'schedule', 'comment' => '进度'],
        'delivery_date_records' => ['name' => 'delivery_date_records', 'comment' => '交货日期'],
        'full_drawing_img' => ['name' => 'full_drawing_img', 'comment' => '图纸'],

    ];
    //查询字段
    public $lists_fields = 'id,name,categorize,model_number,number,drawing_number,delivery_date,drawing_img,create_time,status,order_status,proj_id,estimated_delivery_time,notes,parts_quantity,is_ready';

    public function __construct()
    {
        parent::__construct(app());
        //判断是否是销售部，只有超级管理员与销售部显示 价格 发票 信息
        $department_ids = get_config_cache('department_ids');
        $sales_department_id = $department_ids['sales_department_id'];
        if(in_array($sales_department_id, $this->role_by_user_ids) || $this->is_super_admin == 1)
        {
            $this->index_not_display_fields = 'id,update_time,exception_type,drawing_img'; //重新设置后端列表页显示字段
            $this->lists_fields = 'id,name,categorize,model_number,number,drawing_number,delivery_date,drawing_img,create_time,status,order_status,proj_id,estimated_delivery_time,notes,parts_quantity,invoice_status,price,is_ready';
        }
    }
    public function filter(&$map, &$field)
    {

        //数据表字段
        $field = $this->lists_fields;

        //回收站
        $status = request()->get('status', 0);
        if($status == 3)
        {
            $map = [['status', '=', '3']];
        }else{
            $map = [['status', 'in', '1,2']];
        }

        $title = input('name');
        //项目订单名称
        if(!empty($title)){
            $map[] = ['name', 'like', '%'.$title.'%'];
        }
        //分类
        $categorize = input('categorize');
        if(!empty($categorize)){
            $map[] = ['categorize', '=', $categorize];
        }
        //型号
        $model_number = input('model_number');
        if(!empty($model_number)){
            $map[] = ['model_number', '=', $model_number];
        }
        //图纸编号
        $drawing_number = input('drawing_number');
        if(!empty($drawing_number)){
            $map[] = ['drawing_number', '=', $drawing_number];
        }
        //项目id
        $proj_id = input('proj_id');
        if(!empty($proj_id)){
            $map[] = ['proj_id', '=', $proj_id];
        }
        //创建时间
        $start_time = input('start_time', 0);
        $end_time = input('end_time', 0);
        if (!empty($end_time) && !empty($start_time)) {
            $map[] = ['create_time', 'BETWEEN', [$start_time, $end_time]];
        } else if ($end_time) {
            $map[] = ['create_time', '<', $end_time];
        } else if ($start_time) {
            $map[] = ['create_time', '>', $start_time];
        }

    }

    public function beforeDetail(&$field)
    {
        $field = $this->lists_fields;
    }

    public function finishInsert(&$data)
    {
        //将图纸保存至资料库
        $this->setProjectsDrawingLib($data);

    }

    public function beforeInsert(&$data)
    {
        if(!empty($data['delivery_date']))
        {
            //添加交货日期记录
            $delivery_date_records = [[
                'time' => time(),
                'delivery_date' => $data['delivery_date']
            ]];
            $data['delivery_date_records'] = json_encode($delivery_date_records, JSON_UNESCAPED_UNICODE);
        }else{
            $data['delivery_date_records'] = '';
        }

        //图纸
        if(empty($data['drawing_img']))
        {
            $data['drawing_img'] = '';
        }

        $data['notes'] = empty($data['notes']) ? '' : $data['notes'];
    }


    public function beforeUpdate(&$data)
    {
        //如果交货日期有更改，则记录交货信息。
        $delivery_date = ProjectsOrderM::where('id', $data['id'])->field('delivery_date,delivery_date_records')->find();

        if(!empty($delivery_date['delivery_date_records']))
        {
            $delivery_date_records = json_decode($delivery_date['delivery_date_records'], true);
            $end_data = end($delivery_date_records);
            if($end_data['delivery_date'] != $data['delivery_date'])
            {
                $delivery_date_records[] = [
                    'time' => time(),
                    'delivery_date' => $data['delivery_date']
                ];
                $data['delivery_date_records'] = json_encode($delivery_date_records, JSON_UNESCAPED_UNICODE);;
            }
        }else{
            $data['delivery_date_records'] = '';
        }
        $data['notes'] = empty($data['notes']) ? '' : $data['notes'];

        //图纸
        if(empty($data['drawing_img']))
        {
            $data['drawing_img'] = '';
        }
    }

    public function attachedDetail(&$data)
    {
        //处理交货日期记录
        if(!empty($data['delivery_date_records']))
        {
            $data['delivery_date_records'] = json_decode($data['delivery_date_records'], true);
        }
        //处理图纸图片
        $data['drawing_img'] = json_decode($data['drawing_img']);
        if(!empty($data['drawing_img']) && is_array($data['drawing_img']))
        {
            $data['full_drawing_img'] = [];
            foreach($data['drawing_img'] as $k=>$v)
            {
                $data['full_drawing_img'][] = return_upload_url($v);
            }
        }else{
            $data['drawing_img'] = [];
            $data['full_drawing_img'] = [];
        }

        //判断是否是销售部，只有超级管理员与销售部显示 价格 发票 信息
        $department_ids = get_config_cache('department_ids');
        $sales_department_id = $department_ids['sales_department_id'];
        if(!in_array($sales_department_id, $this->role_by_user_ids))
        {
            if($this->is_super_admin == 0)
            {
                unset($data['price'], $data['invoice_status']);
            }
        }
    }

    public function attachedIndex($data)
    {
       foreach($data as $k=>$v){
           //处理交货日期记录
           if(!empty($v['delivery_date_records']))
           {
               $data[$k]['delivery_date_records'] = json_decode($v['delivery_date_records'], true);
           }

           //判断是否是销售部，只有超级管理员与销售部显示 价格 发票 信息
           $department_ids = get_config_cache('department_ids');
           $sales_department_id = $department_ids['sales_department_id'];
           if($this->is_super_admin == 0)
           {
               if(!in_array($sales_department_id, $this->role_by_user_ids))
               {
                   unset($data[$k]['price'], $data[$k]['invoice_status']);
               }
           }
           //项目进度 查询项目订单完成度
           $data[$k]['schedule'] = (new ProjectsOrderM())->getProjectsOrderSchedule($v['id']);
           //处理图纸图片
           $data[$k]['drawing_img'] = json_decode($v['drawing_img']);
           if(!empty($data[$k]['drawing_img']) && is_array($data[$k]['drawing_img']))
           {
               $data[$k]['full_drawing_img'] = [];
               foreach($data[$k]['drawing_img'] as $key=>$val)
               {
                   $data[$k]['full_drawing_img'][] = return_upload_url($val);
               }
           }else{
               $data[$k]['drawing_img'] = [];
               $data[$k]['full_drawing_img'] = [];
           }
           //是否包含异常状态的零件
           $is_exception =  (new ComponentExceptionInfoRe)->isException($this->run_controller, $v['id']);
           $data[$k]['is_exceprion'] = (bool)$is_exception;
       }
        return $data;
    }

    public function finishUpdate(&$data)
    {
        //将图纸保存至资料库
        $this->setProjectsDrawingLib($data);
    }

    /**
     * Desc: 新增 编辑 将图纸保存至资料库
     * User: 苏鹏
     * Date: 2023/10/7
     * Time: 13:14
     * @return void
     */
    private function setProjectsDrawingLib($data)
    {
        if(!empty($data['drawing_img']))
        {
            //判断图纸是否存在，存在不再保存
            $result = ProjectsDrawingLib::where('image', '=', $data['drawing_img'])->find();
            if(empty($result))
            {
                ProjectsDrawingLib::create(['image'=>$data['drawing_img']]);
            }
        }
    }


    /**
     * Desc: 导入表格
     * User: 苏鹏
     * Date: 2023/10/8
     * Time: 10:22
     * @return void
     */
    public function importExcel()
    {
        $files = request()->file();
        $proj_id = input('proj_id');
        try{
            $validate = validate($this->run_controller);
            //场景验证
            if (!$validate->scene('importExcel')->check(['proj_id' => $proj_id]))
            {
                return re_error_json($validate->getError());
            }

            //仅支持 xlsx
            validate(['image'=>'fileSize:307200|fileExt:xlsx|fileMime:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'])
                ->check($files);
            $savename = [];
            foreach($files as $file) {
                $savename[] = \think\facade\Filesystem::putFile( 'admin', $file);
            }
            if(empty($savename[0])){
                return re_error_json(msg_code(304));
            }
            (new ProjectsOrderS)->projOrderExcelImport('../runtime/storage/'.$savename[0], $proj_id);
        }catch (\Exception $e){
            return re_error_json($e->getMessage());
        }
        return re_success_json();
    }


    /**
     * Desc: 下载导入excel 模板
     * User: 苏鹏
     * Date: 2023/10/8
     * Time: 13:09
     * @return void
     */
    public function downloadExcelTemp()
    {
        try{
            return download($_SERVER['DOCUMENT_ROOT'].'/static/template/projOrderTemp.xlsx', '项目订单excel导入模板.xlsx');
        }catch (\Exception $e){
            return re_error_json($e->getMessage());
        }
    }

    /**
     * Desc: 下载图纸
     * User: 苏鹏
     * Date: 2023/10/8
     * Time: 14:52
     * @return void
     */
    public function downloadDrawing()
    {
        $id = input('id');
        $drawing_img = input('drawing_img');
        try{
            $validate = validate($this->run_controller);
            //场景验证
            if (!$validate->scene('downloadDrawing')->check(['id' => $id,'drawing_img'=>$drawing_img]))
            {
                return re_error_json($validate->getError());
            }
            $projects_order_m = new ProjectsOrderM();
            $name = $projects_order_m->where('id', '=', $id)->where('status', 'in', '1,2')->value('name');
            if(empty($name)){
                $name = '项目订单';
            }
            //检查文件是否存在
            if(file_exists($_SERVER['DOCUMENT_ROOT'].$drawing_img))
            {
                //文件后缀
                $file_attr = pathinfo($drawing_img);
                $file_ext = $file_attr['extension'];
                return download($_SERVER['DOCUMENT_ROOT'].$drawing_img, $name.'_图纸.'.$file_ext);
            }else{
                re_error_json(33); // 文件不存在！
            }

        }catch (\Exception $e){
            return re_error_json($e->getMessage());
        }
        return re_success_json();
    }


    /**
     * Desc: 投入生产
     * User: 苏鹏
     * Date: 2023/10/8
     * Time: 15:39
     * @return void
     */
    public function  production()
    {
        $ids = input('ids');
        $ids = json_decode($ids, true);
        try{
            $projects_order_m = new ProjectsOrderM();
            $projects_order_m->startTrans();
            $validate = validate($this->run_controller);
            //场景验证
            if (!$validate->scene('production')->check(['ids' => $ids]))
            {
                return re_error_json($validate->getError());
            }

            //投入生产前判断订单是否准备就绪

            $count = $projects_order_m->where('id', 'in', $ids)->where('is_ready','=', 1)->count();

            if(!empty($count))
            {
                return re_error_json(msg_code(34)); //项目订单中含有未准备就绪订单，不可以投入生产，请确认后重新提交！
            }

            //投入生产后，项目订单状态修改为 生产中
            $projects_order_m->where('id', 'in', $ids)->update(['order_status'=> 2]);
            //查询项目订单所属项目
            $proj_ids = $projects_order_m->where('id', 'in', $ids)->column('proj_id');
            $proj_ids = array_unique($proj_ids);
            //项目状态修改为 生产中
            (new ProjectsM())->where('id', 'in', $proj_ids)->update(['projects_status'=>2]);
            $projects_order_m->commit();
        }catch (\Exception $e){
            $projects_order_m->rollback();
            return re_error_json($e->getMessage());
        }
        return re_success_json();
    }

    /**
     * Desc: 准备就绪
     * User: 苏鹏
     * Date: 2023-11-15 16:06
     * @return void
     */
    public function ready()
    {
        $id = input('id', 0, 'intval');
        try{
            $projects_order_m = new ProjectsOrderM();
            //查询当前状态，取反状态保存
            $is_ready = $projects_order_m->where('id', '=', $id)->value('is_ready');
            if(!empty($is_ready))
            {
                $is_ready = $is_ready == 1 ? 2 : 1;
                $projects_order_m->where('id', '=', $id)->update(['is_ready'=>$is_ready]);
            }
            $data = [
                'is_ready' => intval($is_ready)
            ];
        }catch (\Exception $e){
            return re_error_json($e->getMessage());
        }
        return re_success_json($data);
    }
}